package com.costeaalex.blueserver.server;

import java.util.Calendar;

import com.costeaalex.blueserver.communication.CommunicationManager;

public class BlueServerSync extends Thread implements BlueServerSenderThread,CommandReceiver
	{

	private CommunicationManager cML;
	private ThreadManager tML;
	private ThreadControl tC;
	private boolean isAlive;
	private boolean isActive;
	private long lastDate=0;
	private long currentDate=0;
	private Calendar calendar;
	private int id=5;
		
	public BlueServerSync(CommunicationManager cM, ThreadManager tM)
		{
		cML=cM;
		tML=tM;
		tC=new ThreadControl();
		isAlive=true;
		isActive=true;
		}
	
	@Override
	public void run()
		{
		super.run();
		tML.push(this, tC);
		
		while(isAlive)
			{
			block();
			if(isActive)
				{
				calendar=Calendar.getInstance();
				currentDate=calendar.getTimeInMillis();
				
				try
					{
					sleep(10);
					}
				catch (InterruptedException e)
					{
					e.printStackTrace();
					}
				
				if((currentDate-lastDate)/1000>2)
					{
					cML.send(new byte[] {1,0,0,2});
					lastDate=currentDate;
					}
				else
					{}
				}
			tML.rotate(this);
			}
		}

	public void activate()
		{
		isActive=true;		
		}

	public void block()
		{
		tC.blockThread();
		}

	public void deActivate()
		{
		isActive=false;
		}

	public boolean isActive()
		{
		return isActive;
		}

	public boolean unblockEligible()
		{
		return true;
		}
	
	public int getServiceId()
		{
		return id;
		}
	
	public void destroy()
		{
		isAlive=false;
		}

	public boolean threadIsAlive()
		{
		return isAlive;
		}

	public int getReceiverId()
		{
		return id;
		}

	public void parseCommand(byte[] command)
		{
		}
	}
